package com.rainy.generator.common.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.rainy.generator.entity.MainMenu;
import lombok.Data;
import lombok.Getter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;


import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Scanner;

/**
 * @author liuqin on 2017/12/19
 */
@Component
@Getter
public class JsonConfig {

    private final static  Logger logger = LoggerFactory.getLogger(JsonConfig.class);

    @Value(value = "classpath:config/template.json")
    private Resource templatePath;

    @Value(value = "classpath:config/menu.json")
    private Resource menu;


    public <T> List<T> getConfigArray(Resource resource, Class<T> clazz){
        List<T> list = Lists.newArrayList();
        try {
            String jsonData = this.jsonRead(resource.getFile());
            list = JSONArray.parseArray(jsonData,clazz);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }

    public <T> T getConfig(Resource resource,Class<T> clazz){
        T  t = null;
        try {
            String jsonData = this.jsonRead(resource.getFile());
            t = JSONObject.parseObject(jsonData,clazz);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return t;
    }

    /**
     *   读取文件类容为字符串
     */
    private String jsonRead(File file){
        Scanner scanner = null;
        StringBuilder buffer = new StringBuilder();
        try {
            scanner = new Scanner(file, "utf-8");
            while (scanner.hasNextLine()) {
                buffer.append(scanner.nextLine());
            }
        } catch (Exception e) {
            logger.error("jsonRead:"+e);
        } finally {
            if (scanner != null) {
                scanner.close();
            }
        }
        return buffer.toString();
    }
}
